package com.guxingke.typecho4j.widget.provider.base;

import javax.servlet.http.HttpSession;

import com.guxingke.typecho4j.Typecho4jException;
import com.guxingke.typecho4j.jfinal.model.User;
import com.guxingke.typecho4j.widget.WidgetProvider;
import com.guxingke.typecho4j.widget.provider.UserBaseWidget;
import com.jfinal.core.Controller;

/**
 * 共同依赖的基础模块之用户组件
 * 
 * @author guxingke
 * */
public class UserWidget extends UserBaseWidget implements WidgetProvider {

	@Override
	public void excute(Controller controller) {
		HttpSession session = controller.getSession();
		User user = null;

		Boolean isCheckedCookie = (Boolean) session
				.getAttribute("isCheckedCookie");
		if (isCheckedCookie == null || !isCheckedCookie) {
			String cookieUser = controller.getCookie("user");
			if (cookieUser != null) {
				String[] temps = cookieUser.split("-");
				String username = temps[0];
				String password = temps[1];

				try {
					user = login(username, password);
				} catch (Typecho4jException e) {
					session.setAttribute("isCheckedCookie",
							true);
				}

				if (user != null) {
					updateLogged(user);
					updateActivated(user);
					session.setAttribute("user", user);
				}

				session.setAttribute("isCheckedCookie", true);
			}
		} else {
			user = (User) session.getAttribute("user");
			if (user != null) {
				updateActivated(user);
			}
		}

	}

	@Override
	public void refresh() {
	}
}
